<script setup lang="ts" generic="T extends TableData">
  import { useI18n } from 'vue-i18n';
  import type {
    DropdownInstance,
    TableColumnData,
    TableData,
    TableInstance,
  } from '@arco-design/web-vue';
  import { ref, computed, useAttrs, watch, useSlots } from 'vue';
  import { VueDraggable } from 'vue-draggable-plus';

  defineOptions({ name: 'BhTable', inheritAttrs: false });
  const emit = defineEmits<{
    (e: 'refresh'): void;
  }>();
  interface Props {
    title?: string;
    data: T[];
    disabledTools?: string[];
    disabledColumnKeys?: string[];
  }
  const props = withDefaults(defineProps<Props>(), {
    title: '', // 标题
    data: () => [], // 数据
    disabledTools: () => [], // 禁止显示的工具
    disabledColumnKeys: () => [], // 禁止控制显示隐藏的列
  });
  const { t } = useI18n();
  const attrs = useAttrs();
  const slots = useSlots();
  // 是否全屏
  const isFullscreen = ref(false);
  // 是否显示刷新按钮
  const showRefreshBtn = computed(
    () => !props.disabledTools.includes('refresh')
  );
  // 是否展示尺寸按钮
  const showSizeBtn = computed(() => !props.disabledTools.includes('medium'));
  const showSettingColumnBtn = computed(
    () =>
      !props.disabledTools.includes('setting') &&
      attrs?.columns &&
      (attrs?.columns as TableColumnData[])?.length
  );
  const showFullscreenBtn = computed(
    () => !props.disabledTools.includes('fullscreen')
  );
  // 列设置
  interface SettingColumnItem {
    title: string;
    key: string;
    show: boolean;
    disabled: boolean;
  }
  const settingColumnList = ref<SettingColumnItem[]>([]);

  // 重置配置列
  const resetSettingColumns = () => {
    settingColumnList.value = [];
    if (attrs.columns) {
      const arr = attrs.columns as TableColumnData[];
      arr.forEach((item) => {
        settingColumnList.value.push({
          key:
            item.dataIndex ||
            (typeof item.title === 'string' ? item.title : ''),
          title: typeof item.title === 'string' ? item.title : '',
          show: item?.show ?? true,
          disabled: props.disabledColumnKeys.includes(
            item.dataIndex || (typeof item.title === 'string' ? item.title : '')
          ),
        });
      });
    }
  };

  // 尺寸配置
  type SizeProps = 'mini' | 'small' | 'medium' | 'large';
  const densityList = computed(() => [
    {
      name: t('searchTable.size.mini'),
      value: 'mini',
    },
    {
      name: t('searchTable.size.small'),
      value: 'small',
    },
    {
      name: t('searchTable.size.medium'),
      value: 'medium',
    },
    {
      name: t('searchTable.size.large'),
      value: 'large',
    },
  ]);
  const size = ref<SizeProps>('medium');
  const handleSelectDensity = (
    val: string | number | Record<string, any> | undefined,
    e: Event
  ) => {
    size.value = val as SizeProps;
  };

  watch(
    () => attrs,
    () => {
      resetSettingColumns();
    },
    { immediate: true }
  );
  const tableRef = ref<TableInstance | null>(null);
  const stripe = ref(false);
  const isBordered = ref(false);
  const refresh = () => {
    emit('refresh');
  };
  // 排序和过滤可显示的列数据

  const showColumns = computed(() => {
    if (!attrs.columns) return [];
    const arr = attrs.columns as TableColumnData[];
    // 显示的dataIndex
    const showDataIndexs = settingColumnList.value
      .filter((i) => i.show)
      .map((i) => i.key || (typeof i.title === 'string' ? i.title : ''));
    // 显示的columns数据
    const filterColumns = arr.filter((i) =>
      showDataIndexs.includes(
        i.dataIndex || (typeof i.title === 'string' ? i.title : '')
      )
    );
    const sortedColumns: TableColumnData[] = [];
    settingColumnList.value.forEach((i) => {
      filterColumns.forEach((j) => {
        if (i.key === (j.dataIndex || j.title)) {
          sortedColumns.push(j);
        }
      });
    });
    return sortedColumns;
  });

  defineExpose({ tableRef });
</script>

<template>
  <!-- 搜索 -->
  <a-card class="general-card" :class="{ 'table-search-card':props.title }" >
    <!-- 表格标题-->
    <a-row
        v-if="props.title"
        justify="space-between"
        align="center"
        class="bh-table__header "
    >
      <a-space wrap>
        <slot name="custom-title">
          <div class="bh-table__header-title">{{ props.title }}</div>
        </slot>
      </a-space>
    </a-row>
    <slot name="top"></slot>
  </a-card>
  <div class="bh-table" :class="{ 'bh-table--fullscreen': isFullscreen }">
    <!-- 操作栏-->
    <a-row
      justify="space-between"
      align="center"
      class="bh-table__toolbar"
      style="display: flex; align-items: center; "
    >
      <a-space wrap class="bh-table__toolbar-left" :size="[8, 8]">
        <!-- 自定义插槽-->
        <slot name="toolbar-left"></slot>
      </a-space>

      <a-space wrap class="bh-table__toolbar-right" :size="[8, 8]">
        <!-- 自定义插槽-->
        <slot name="toolbar-right"></slot>
        <!-- 刷新-->
        <a-tooltip :content="$t('common.refresh')">
          <a-button v-if="showRefreshBtn" @click="refresh">
            <template #icon>
            <IconRefresh size="16"/>
            </template>
          </a-button>
        </a-tooltip>
        <!-- 尺寸-->
        <a-dropdown v-if="showSizeBtn" @select="handleSelectDensity">
          <a-tooltip :content="$t('common.density')">
            <a-button >
              <icon-line-height size="16" />
            </a-button>
          </a-tooltip>
          <template #content>
            <a-doption
              v-for="item in densityList"
              :key="item.value"
              :value="item.value"
              :class="{ active: item.value === size }"
            >
              <span>{{ item.name }}</span>
            </a-doption>
          </template>
        </a-dropdown>
        <!-- 列设置-->
        <a-popover
          v-if="showSettingColumnBtn"
          trigger="click"
          position="br"
          :content-style="{ minWidth: '120px', padding: '6px 8px 10px' }"
        >
          <a-tooltip content="列设置">
            <a-button>
              <template #icon>
                <icon-settings />
              </template>
            </a-button>
          </a-tooltip>
          <template #content>
            <div class="bh-table__draggable">
              <VueDraggable v-model="settingColumnList">
                <div
                  v-for="item in settingColumnList"
                  :key="item.title"
                  class="drag-item"
                >
                  <div class="drag-item__move"><icon-drag-dot-vertical /></div>
                  <a-checkbox
                    v-model:model-value="item.show"
                    :disabled="item.disabled"
                    >{{ item.title }}</a-checkbox
                  >
                </div>
              </VueDraggable>
            </div>
            <a-divider :margin="6" />
            <a-row justify="center">
              <a-button
                type="primary"
                size="mini"
                long
                @click="resetSettingColumns"
              >
                <template #icon><icon-refresh /></template>
                <template #default>重置</template>
              </a-button>
            </a-row>
          </template>
        </a-popover>
        <!-- 全屏-->
        <a-tooltip content="全屏">
          <a-button
            v-if="showFullscreenBtn"
            @click="isFullscreen = !isFullscreen"
          >
            <template #icon>
            <icon-fullscreen v-if="!isFullscreen" size="16" />
            <icon-fullscreen-exit v-else size="16" />
            </template>
            </a-button>
        </a-tooltip>
      </a-space>
    </a-row>
    <!-- 数据栏-->
    <div
      class="bh-table__body"
      :class="`bh-table__body-pagination-${attrs['page-position']}`"
    >
      <div class="bh-table__container">
        <a-table
          ref="tableRef"
          :stripe="stripe"
          :size="size"
          column-resizable
          :bordered="{ cell: isBordered }"
          v-bind="{ ...attrs, columns: showColumns }"
          :scrollbar="true"
          :data="data"
        >
          <template
            v-for="key in Object.keys(slots)"
            :key="key"
            #[key]="scoped"
          >
            <slot :key="key" :name="key" v-bind="scoped"></slot>
          </template>
        </a-table>
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
.table-search-card {
  width: 100%;
  margin-bottom: 16px;
}
.general-card {
  border-radius: 4px;
  border: none;
}
  .bh-table {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    height: 100%;
    background: var(--color-bg-1);
    position: relative;
    box-sizing: border-box;
    padding: 10px;
  }
  .bh-table.bh-table--fullscreen {
    padding: @padding;
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    z-index: 1001;
  }
   .bh-table-bh-table__body{
     position: relative;
     display: flex;
     flex-direction: column;
     flex: 1;
     overflow: auto;
   }
  //如果为空时，将表格铺满
  :deep(.arco-table-element):has(tbody .arco-table-tr-empty) {
    height: 100%;
  }
  // 分页默认位置
  :deep(.arco-pagination) {
    margin-top: 10px;
    justify-content: end;
  }
  .bh-table__body-pagination {
    flex-direction: column-reverse;

  }
  :deep(.bh-table__body-pagination.arco-pagination) {
    margin-bottom: 10px;
    justify-content: center;
  }

  .bh-table__container {
    max-height: 100%;
    overflow: hidden;
    flex: 1;
  }
  :deep(.arco-table-border:not(.arco-table-border-cell) .arco-table-container) {
    height: 100%;
  }
  :deep(.arco-table-body) {
    height: 100%;
  }
  // 控制表格最后一行的下边框显示
  :deep(
      .arco-table-border
        .arco-table-scroll-y
        .arco-table-body
        .arco-table-tr:last-of-type
        .arco-table-td,
      .arco-table-border
        .arco-table-scroll-y
        tfoot
        .arco-table-tr:last-of-type
        .arco-table-td
    ) {
    border-bottom: 1px solid var(--color-border-table);
  }

  .bh-table__header {
    padding: 0 0 10px;
  }
  .bh-table__header-title {
    color: var(--color-text-1);
    font-size: 18px;
    font-weight: 500;
    line-height: 1.5;
  }
  :deep(.arco-form-item-layout-inline) {
    margin-right: 8px;
  }
  :deep(.arco-form-item-layout-inline:last-of-type) {
    margin-right: 0;
  }
  .bh-table__draggable {
    padding: 1px 0;
    max-height: 250px;
    box-sizing: border-box;
    overflow: hidden;
    overflow-y: auto;
  }

  .drag-item {
    display: flex;
    align-items: center;
    cursor: pointer;
  }
  .drag-item:hover {
    background-color: var(--color-fill-2);
  }
  .drag-item__move {
    padding-left: 2px;
    padding-right: 2px;
    cursor: move;
  }
  :deep(.arco-checkbox) {
    width: 100%;
    font-size: 12px;
    padding-left: 15px;
  }
  :deep(.arco-checkbox.arco-checkbox-icon) {
    width: 14px;
    height: 14px;
  }
</style>
